package com.ceres.customer.service.impl;

import com.ceres.customer.dao.CustMapper;
import com.ceres.customer.dao.CustUserMapper;
import com.ceres.customer.pojo.Customer;
import com.ceres.customer.pojo.User;
import com.ceres.customer.service.CustService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CustServiceImpl implements CustService {

    @Autowired
    private CustMapper custMapper;

    @Autowired
    private CustUserMapper custUserMapper;

    /**
     * 农业组织添加方法
     *
     * @param customer
     */
    @Override
    public void add(Customer customer) {
        //添加农业组织
        customer.setStatus("0");
        customer.setActiveTime(new Date());
        customer.setCreateTime(new Date());
        custMapper.insertSelective(customer);
        int customerId = customer.getId();

        //密码加盐加密
        String gensalt = BCrypt.gensalt();
        String password = BCrypt.hashpw("123456", gensalt);
        //添加一个农场主
        User user = new User();
        user.setName(customer.getContacts());
        user.setUsername(customer.getCode());
        user.setPassword(password);
        user.setStatus("1");
        user.setCustomerId(customerId);

        custUserMapper.insertSelective(user);
    }

    /**
     * 修改农业组织
     *
     * @param customer
     */
    @Override
    public void update(Customer customer) {
        //先根据id查询农业组织对象
        Customer customer1 = custMapper.selectByPrimaryKey(customer.getId());
        //将前端传入的对象中的属性封装进查询出的对象
        customer1.setName(customer.getName());
        customer1.setCode(customer.getCode());
        customer1.setAddress(customer.getAddress());
        customer1.setContacts(customer.getContacts());
        customer1.setPhone(customer.getPhone());
        customer1.setEmail(customer.getEmail());
        customer1.setEndTime(customer.getEndTime());
        customer1.setStatus(customer.getStatus());
        custMapper.updateByPrimaryKeySelective(customer1);
    }

    /**
     * 分页模糊查询农业组织
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<Customer> findPage(String keyword, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return (Page<Customer>) custMapper.findByKeyWord(keyword);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Override
    public Customer findById(int id) {
        return custMapper.selectByPrimaryKey(id);
    }
}
